package com.shuoren.roomtemperaturecloud.repository;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import com.shuoren.roomtemperaturecloud.entity.HistoryData;
import com.shuoren.roomtemperaturecloud.entity.PageDataInfo;

/**
 * @Author: Yann
 * @Date: 2019/1/3 14:20
 */
@Repository
public class HistoryRepository {

	@Autowired
	MongoTemplate mongoTemplate;

	public PageDataInfo getListHistory(String d_id, long startTime, long endTime, int pageNo, int pageSize) {
		
		// 创建查询对象
		Query query = new Query();
		// 设置起始数
		query.skip((pageNo - 1) * pageSize);
		// 设置查询条数
		query.limit(pageSize);
		// 创建条件对象
		Criteria criteria = new Criteria();
		
		// 添加设备id条件过滤
		criteria.and("deviceid").is(d_id);
		
		if (startTime!=0&endTime!=0) {
			// 开始时间验证   结束时间验证
			criteria.and("ca").gte(startTime).lt(endTime);
		}
		
		query.addCriteria(criteria);

		//查询数据
		List<HistoryData> historydata= mongoTemplate.find(query,HistoryData.class, "historydata");
		//查询结果
		PageDataInfo pdi = new PageDataInfo();
		pdi.setPageNo(pageNo);
		pdi.setPageSize(pageSize);
		//设置总条数
		pdi.setTotalCount((int)mongoTemplate.count(query, HistoryData.class));
		pdi.setTotalPage(pdi.getTotalCount()%pageSize==0?1:pdi.getTotalCount()/pageSize+1);
		
		pdi.setDatas(historydata);
		return pdi;
	}
}
